<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>文档检索</title>
    <link rel="stylesheet" href="./lib/element-plus/index.css">
    <style>
        /* 整体容器样式 */
        .search-container {
            max-width: 1000px;
            margin: 20px auto;
            padding: 24px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        /* 表单字段间距 */
        .search-form .el-form-item {
            margin-bottom: 20px;
        }

        /* 输入框组横向排列 */
        .input-group {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            gap: 10px;
        }

        /* 单个输入框行样式 */
        .input-row {
            display: flex;
            gap: 10px;
            align-items: center;
            min-width: 280px; /* 保证输入框不会过窄 */
        }

        /* 追加按钮特效 */
        .add-btn {
            align-self: center;
            margin-top: 0;
            transition: all 0.2s ease;
        }
        .add-btn:hover {
            transform: scale(1.05);
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
        }
        .add-btn:active {
            transform: scale(0.95);
            box-shadow: none;
        }

        /* 移除按钮特效 */
        .remove-btn {
            transition: all 0.2s ease;
        }
        .remove-btn:hover {
            transform: scale(1.05);
            box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
        }
        .remove-btn:active {
            transform: scale(0.95);
            box-shadow: none;
        }

        /* 排序按钮组间距 */
        .type-group {
            margin: 20px 0;
        }

        /* 结果容器样式 */
        .result-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 24px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        /* 表格样式 */
        .el-table {
            margin-top: 16px;
        }

        /* 输入框最小宽度 */
        .el-input {
            min-width: 200px;
        }

        /* 小按钮内边距 */
        .el-button--small {
            padding: 4px 8px;
        }

        /* 文本截断样式 */
        .ellipsis {
            max-width: 180px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: inline-block;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 检索条件卡片 -->
    <el-card class="search-container">
        <h3>文档检索条件</h3>
        <el-form :model="tagForm" label-width="220px" class="search-form" label-position="left">
            <!-- 动态参数输入模板（循环生成7个字段） -->
            <template v-for="(field, index) in fields" :key="index">
                <el-form-item :label="field.label">
                    <div class="input-group">
                        <!-- 输入框行（输入框+移除按钮） -->
                        <div v-for="(item, inputIndex) in tagForm[field.key]" :key="inputIndex" class="input-row">
                            <el-input
                                    v-model="tagForm[field.key][inputIndex]"
                                    :placeholder="field.placeholder"
                                    clearable
                            ></el-input>
                            <el-button
                                    type="danger"
                                    size="small"
                                    @click="removeInput(field.key, inputIndex)"
                                    v-if="tagForm[field.key].length > 1"
                                    class="remove-btn"
                            >
                                移除
                            </el-button>
                        </div>
                        <!-- 追加条件按钮 -->
                        <el-button
                                type="primary"
                                size="small"
                                @click="addInput(field.key)"
                                class="add-btn"
                        >
                            追加条件
                        </el-button>
                    </div>
                </el-form-item>
            </template>
        </el-form>

        <!-- 排序类型选择 -->
        <el-radio-group v-model="sortType" size="large" class="type-group">
            <el-radio-button label="day">日浏览量</el-radio-button>
            <el-radio-button label="week">周浏览量</el-radio-button>
            <el-radio-button label="month">月浏览量</el-radio-button>
        </el-radio-group>

        <!-- 检索按钮 -->
        <el-button style="margin-top: 10px;margin-left: 30px;"
                type="success"
                @click="handleSearch"
                :loading="isLoading"
                class="search-btn"
        >
            {{ isLoading ? '检索中...' : '立即检索' }}
        </el-button>
    </el-card>

    <!-- 检索结果卡片 -->
    <el-card class="result-container" v-if="resultList.length">
        <h3>{{ getSortTypeText() }}浏览量前10条结果</h3>
        <el-table
                :data="resultList"
                border
                stripe
                fit
                :header-cell-style="{ background: '#f5f7fa' }"
        >
            <el-table-column prop="doc_id" label="文档ID" width="180" align="center"></el-table-column>
            <el-table-column prop="title" label="文档标题" min-width="200">
                <template #default="scope">
                    <el-tooltip effect="dark" :content="scope.row.title" placement="top">
                        <span class="ellipsis">{{ scope.row.title }}</span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="content" label="内容摘要" width="400" align="center">
                <template #default="scope">
                    <el-tooltip effect="dark" :content="scope.row.content" placement="top">
                        <span class="ellipsis">{{ scope.row.content }}</span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column
                    v-if="sortType === 'day'"
                    prop="daily_view_count"
                    label="日浏览量"
                    width="120"
                    align="cneter"
            ></el-table-column>
            <el-table-column
                    v-if="sortType === 'week'"
                    prop="weekly_view_count"
                    label="周浏览量"
                    width="120"
                    align="cneter"
            ></el-table-column>
            <el-table-column
                    v-if="sortType === 'month'"
                    prop="monthly_view_count"
                    label="月浏览量"
                    width="120"
                    align="cneter"
            ></el-table-column>
            <el-table-column
                    prop="create_time"
                    label="创建时间"
                    width="200"
                    align="center"
            >
                <template #default="scope">
                    {{ formatDate(scope.row.create_time) }}
                </template>
            </el-table-column>
        </el-table>
    </el-card>

    <!-- 无结果提示 -->
    <el-empty
            description="未找到符合条件的文档"
            v-else-if="!isLoading"
    ></el-empty>
</div>

<!-- 依赖库引入 -->
<script src="./lib/vue/vue.global.js"></script>
<script src="./lib/element-plus/index.full.js"></script>
<script src="./lib/axios/axios.min.js"></script>
<script src="./lib/util/lodash.min.js"></script>

<script>
    const { createApp, ref, watch } = Vue;
    const _ = window._; // 引入lodash的防抖函数
    const { ElMessage } = ElementPlus; // 从ElementPlus中解构ElMessage


    createApp({
        setup() {
            // 配置参数元信息（统一维护字段标签和提示）
            const fields = ref([
                { key: 'area', label: '适用地区（area）', placeholder: '示例：cn/us/eu' },
                { key: 'product', label: '适用产品（product）', placeholder: '示例：Q3/product_b' },
                { key: 'language', label: '适用语言（language）', placeholder: '示例：zh-CN/en-US' },
                { key: 'secretLevel', label: '保密等级（secretLevel）', placeholder: '示例：public/secret' },
                { key: 'channel', label: '适用渠道（channel）', placeholder: '示例：web/app' },
                { key: 'object', label: '使用对象（object）', placeholder: '示例：user/admin' },
                { key: 'businessAttribute', label: '业务属性（businessAttribute）', placeholder: '示例：finance/marketing' }
            ]);

            // 初始化表单数据（每个字段默认1个空输入框）
            const tagForm = ref({
                area: [''],
                product: [''],
                language: [''],
                secretLevel: [''],
                channel: [''],
                object: [''],
                businessAttribute: ['']
            });

            const sortType = ref('day'); // 默认排序类型
            const resultList = ref([]);   // 检索结果列表
            const isLoading = ref(false); // 加载状态

            // 日期格式化函数
            const formatDate = (timestamp) => {
                return new Date(timestamp).toLocaleString('zh-CN', {
                    year: 'numeric', month: '2-digit', day: '2-digit',
                    hour: '2-digit', minute: '2-digit'
                });
            };

            // 获取排序类型文本描述
            const getSortTypeText = () => {
                return { day: '日', week: '周', month: '月' }[sortType.value];
            };

            // 动态添加输入框
            const addInput = (fieldKey) => {
                tagForm.value[fieldKey].push(''); // 向对应字段数组追加空值
            };

            // 动态移除输入框（至少保留1个）
            const removeInput = (fieldKey, index) => {
                if (tagForm.value[fieldKey].length > 1) {
                    tagForm.value[fieldKey].splice(index, 1); // 从数组中移除指定索引项
                }
            };

            // 防抖搜索函数（300ms）
            const debouncedSearch = _.debounce(async () => {
                if (isLoading.value) return; // 加载中时跳过请求
                await handleSearch();
            }, 300);

            // 监听排序类型变化，触发防抖搜索
            watch(sortType, () => {
                debouncedSearch();
            });

            // 核心检索逻辑
            const handleSearch = async () => {
                isLoading.value = true; // 开启加载状态
                try {
                    // 构建请求参数（过滤空值并数组化）
                    const requestBody = {
                        sortType: sortType.value
                    };

                    // 遍历所有字段处理参数
                    fields.value.forEach(field => {
                        const values = tagForm.value[field.key]
                            .map(v => v.trim())        // 去除首尾空格
                            .filter(v => v !== '');    // 过滤空字符串

                        if (values.length > 0) {
                            requestBody[field.key] = values; // 非空值保留为数组
                        }
                    });

                    // 发送POST请求
                    const res = await axios.post('/esProject/api/search', requestBody, {
                        timeout: 15000, // 15秒超时
                        headers: { 'Content-Type': 'application/json' }
                    });

                    // 处理响应结果
                    resultList.value = res.data.data || [];
                    if (resultList.value.length === 0) {
                        ElMessage.info('未找到匹配的文档');
                    }
                } catch (error) {
                    // 错误处理
                    console.error('检索失败:', error);
                    ElMessage.error('检索失败，请检查网络或参数');
                } finally {
                    isLoading.value = false; // 关闭加载状态
                }
            };


            handleSearch();

            return {
                fields,
                tagForm,
                sortType,
                resultList,
                isLoading,
                formatDate,
                getSortTypeText,
                addInput,
                removeInput,
                handleSearch,
                debouncedSearch
            };
        }
    })
        .use(ElementPlus) // 注册Element Plus组件
        .mount('#app');   // 挂载到DOM
</script>
</body>
</html>
